package com.base.controller;

import com.base.service.RepositorySourceService;
import com.base.utils.Result;
import com.base.utils.ResultUtil;
import com.base.vo.PageRequestHelperVo;
import com.base.vo.RepositorySource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;

/**
 * @author wnhuang
 * @Package com.base.controller
 * @date 2021-03-12 16:18
 */
@Api(value = "数据源管理API", tags = "维护所有数据库连接")
@RestController
@RequestMapping("/RepositorySource")
public class RepositorySourceController {

    @Autowired
    RepositorySourceService repositorySourceService;


    @ApiOperation(value = "查询数据库连接列表")
    @ApiImplicitParam(name = "pageRequestHelperVo", value = "封装的分页请求对象", required = true, dataType = "json", dataTypeClass = PageRequestHelperVo.class,paramType = "query")
    @GetMapping("/getList")
    public Result getList(PageRequestHelperVo pageRequestHelperVo) {
        return ResultUtil.success(repositorySourceService.page(pageRequestHelperVo));
    }

    @ApiOperation(value = "校验数据库连接是否正常")
    @PostMapping("/validConnection")
    public Result validConnection(@RequestBody RepositorySource repositorySource) throws SQLException {
        return ResultUtil.success(repositorySourceService.testConnection(repositorySource));
    }

    @ApiOperation(value = "新增、修改数据库连接")
    @PostMapping("/save")
    public Result saveRepositorySource(@RequestBody RepositorySource repositorySource) {
        repositorySourceService.saveOrUpdate(repositorySource);
        return ResultUtil.success(repositorySource);
    }

//    @PostMapping("/add")
//    @ApiOperation("通用添加数据源（推荐）")
//    public Set<String> add(@Validated @RequestBody RepositorySource repositorySource) {
//        DataSourceProperty dataSourceProperty = new DataSourceProperty();
//        BeanUtils.copyProperties(repositorySource,dataSourceProperty);
//        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
//        DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
//        ds.addDataSource(repositorySource.getName(), dataSource);
//        return ds.getCurrentDataSources().keySet();
//    }
//
//    @DeleteMapping
//    @ApiOperation("删除数据源")
//    public String remove(String name) {
//        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
//        ds.removeDataSource(name);
//        return "删除成功";
//    }

}
